package org.Panel;

import javafx.beans.value.WritableDoubleValue;
import org.Component.ScrollBar;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

public class ScrollPanel extends JPanel {

    public int WIDTH = 1000;
    public int HEIGHT = 600;
    //显示框显示的高度,也是内置界面的高度
    int INH = 10;
    //内置面板
    JPanel Inpanel = new JPanel();
    //滑动条
    ScrollBar scrollBar = new ScrollBar();
    // 创建一个简单的线边框，颜色为黑色，粗细为1像素
    Border border = BorderFactory.createLineBorder(Color.BLACK, 1);

    public ScrollPanel(int width, int height) {

        WIDTH = width;
        HEIGHT = height;

        setBounds(0,0,WIDTH,HEIGHT);
        setLayout(null);
        setBorder(border);

        //初始面板设置
        Inpanel.setLayout(null);
        Inpanel.setBounds(0,0,WIDTH,HEIGHT*3);

        //滑动条,置于内部界面的右侧
        scrollBar.setLocation(Inpanel.getWidth()-10,0);
        scrollBar.limitY = getHeight();

        add(scrollBar);
        add(Inpanel);

        //鼠标滚动事件
        addMouseWheelListener(new MouseWheelListener() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                int wheel = e.getWheelRotation();
                if(wheel > 0) {
                    if(scrollBar.getY()<getHeight()-scrollBar.getHeight()) {
                        scrollBar.setLocation(Inpanel.getWidth()-10,scrollBar.getY()+wheel);
                    }
                }else {
                    if(scrollBar.getY()>0) {
                        scrollBar.setLocation(Inpanel.getWidth()-10,scrollBar.getY()+wheel);
                    }
                }
                System.out.println(scrollBar.getY());
            }
        });


    }

    //更新配置
    public void update() {
        WIDTH = getWidth();
        HEIGHT = getHeight();
        scrollBar.setLocation(Inpanel.getWidth()-10,scrollBar.getY());

    }

    //设置内置面板
    public void setPanel(JPanel panel) {
        remove(Inpanel);
        Inpanel = panel;
        add(Inpanel);
    }

    //添加控件至内置界面
    public void addPanel(JPanel panel) {
        Inpanel.add(panel);
        INH += panel.getPreferredSize().height;
    }

    //逻辑运行
    public void run() {
        //更新内置面板的大小
//        Inpanel.setSize(Inpanel.getWidth(),INH);

        scrollBar.setLocation(Inpanel.getWidth()-10,scrollBar.getY());

        //防止滑动条出界
        if(scrollBar.getY()<0){ //上界
            scrollBar.setLocation(Inpanel.getWidth()-10,0);
        }
        if(scrollBar.getY()>getHeight()-scrollBar.getHeight()) {    //下界
            scrollBar.setLocation(Inpanel.getWidth()-10,getHeight()-scrollBar.getHeight());
        }

//        scrollBar.run();
        //让内置面板的位置随着滑动条改变
        int dh = Inpanel.getHeight()-getHeight();
        if(dh<0) dh=0;
        Inpanel.setLocation(Inpanel.getX(),-dh*scrollBar.getY()/(getHeight()-scrollBar.getHeight()));
        repaint();

    }

}
